package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.IWmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserService extends ServiceImpl<WmUserMapper, WmUser> implements IWmUserService {
    @Override
    public ResponseResult login(WmUserDTO wmUserDTO) {
        //1.校验参数
        if(StringUtils.isBlank(wmUserDTO.getName()) || StringUtils.isBlank(wmUserDTO.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码不能为空");
        }
        //2.根据用户名查询用户
        WmUser wmUser = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, wmUserDTO.getName()));
        if(wmUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "登录账号不存在");
        }
        //3.校验密码
        String password = wmUser.getPassword();
        String digestPassword = DigestUtils.md5DigestAsHex((wmUserDTO.getPassword() + wmUser.getSalt()).getBytes());
        if(!password.equals(digestPassword)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //4.检查登录账号状态
        if(!wmUser.getStatus().equals(AdminConstants.USER_STATUS_OK)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //5.修改登陆时间
        wmUser.setLoginTime(new Date());
        this.updateById(wmUser);
        //6.颁发 Token
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
        //7.返回响应(令牌 +　用户信息)
        Map result = new HashMap<String, Object>();
        WmUserVO wmUserVO = new WmUserVO();
        BeanUtils.copyProperties(wmUser,wmUserVO);
        result.put("token", token);
        result.put("user", wmUserVO);
        return ResponseResult.okResult(result);
    }
}